package codeRandomThoughts.Test22括号生成;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    StringBuilder path = new StringBuilder();
    List<String> result = new ArrayList<>();
    int leftNum = 1;
    int rightNum = 0;

    public List<String> generateParenthesis(int n) {
        path.append('(');
        backtrack(n);
        return result;
    }

    public void backtrack(int n) {
        //终止条件
        if (path.length() == 2 * n) {
            result.add(new String(path));
            return;
        }

        //横向搜索,先添加左括号,再添加右括号
        //左括号没有用完时,添加左括号
        if (leftNum < n) {
            path.append('(');
            leftNum++;
            backtrack(n);
            leftNum--;
            path.deleteCharAt(path.length() - 1);
        }

        //右括号数量必须小于左括号数量
        if (rightNum < leftNum) {
            rightNum++;
            path.append(')');
            backtrack(n);
            path.deleteCharAt(path.length() - 1);
            rightNum--;
        }
    }
}
